//导入数据库模块
const db = require('../db/index.js')

// 导入加密模块 bcryptjs 
const bcrypt = require('bcryptjs')

// 导入jwt模块
const jwt = require('jsonwebtoken')

//定义密钥
const secret = 'secretKey'

exports.addArticle = (req, res) => {
    const artContent = req.body
    console.log(artContent)
    console.log(artContent.title)

    const sqlStr = 'INSERT INTO article (title, category, content, date) VALUES (?, ?, ?, ?)'
    db.query(sqlStr, [artContent.title, artContent.category, artContent.content, artContent.date], (err, results) => {
        if (err) {
            console.log(err.message)
            return res.cc(err)
        } 
        if (results.affectedRows === 1) {
            console.log('新闻添加成功')
            res.send({
                status: 0,
                message: '添加成功'
            })
        }
    })
    // res.send('ok,zaizheli')
}


//获取文章列表
exports.getArticle = (req, res) => {
    console.log(req.headers,"获取文章列表")
    console.log(req.query)
    const category = req.query.category

            if (category || category === 0) {
                const sqlStr = 'SELECT * FROM article WHERE category = ?'
                db.query(sqlStr, [category], (err, results) => {
                // console.log(results)
                res.send(results)
            })
            } else {
                const sqlStr = 'SELECT * FROM article'
                db.query(sqlStr, (err, results) => {
                    res.send(results)
                })
            }
        // }
    // })





    
}


// 通过id获取新闻详情
exports.getDetail = (req, res) => {
    const id = req.query.id
    console.log(id)
    const sqlStr = 'SELECT * FROM article WHERE id = ?'
    db.query(sqlStr, [id], (err, results) => {
        res.send(results)
    })
}

//通过id删除新闻
exports.deleteArticle = (req, res) => {
    const id = req.query.id
    console.log(id, "删除id")
    const sqlStr = 'DELETE FROM article WHERE id=?'
    db.query(sqlStr, [id], (err, results) => {
        if (err) {
            console.log(err, message)
            return res.send({
                status: 1,
                message: '删除失败'
            })
        } 
        if (results.affectedRows === 1) {
            console.log('删除成功')
            res.send({
                status: 0,
                message: "删除成功"
            })
        }
    })

}